package utils

import (
	"encoding/json"
	"gitee.com/chejiangyi/bsfgo/core/base2"
)

var JsonUtil = &JsonUtilTool{}

type JsonUtilTool struct{}

func (*JsonUtilTool) FromJsonWithBytes(jsonBytes []byte, obj interface{}) any {
	err := json.Unmarshal(jsonBytes, obj)
	if err != nil {
		panic(base2.NewBsfError2("json反序列化失败", err))
	}
	return obj
}

func (m *JsonUtilTool) FromJson(jsonStr string, obj interface{}) any {
	return m.FromJsonWithBytes([]byte(jsonStr), obj)
}

func (*JsonUtilTool) ToJsonWithBytes(obj interface{}) []byte {
	jsonBytes, err := json.Marshal(obj)
	if err != nil {
		panic(base2.NewBsfError2("json序列化失败", err))
	}
	return jsonBytes
}

func (m *JsonUtilTool) ToJson(obj interface{}) string {
	return string(m.ToJsonWithBytes(obj))
}
